<?php
namespace app\lib\model;
/**
 * https://cloud.tencent.com/product/faceid/pricing
 * 腾讯实名认证（faceid）
 * https://gitee.com/tencentcloud/tencentcloud-sdk-php
 */
use think\facade\Log;
use TencentCloud\Faceid\V20180301\FaceidClient;


use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
use TencentCloud;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Faceid\V20180301\Models\CheckIdCardInformationRequest;
use TencentCloud\Faceid\V20180301\Models\IdCardVerificationRequest;

use TencentCloud\Iai\V20200303\IaiClient;
use TencentCloud\Iai\V20200303\Models\CreateGroupRequest;  //创建人员库
use TencentCloud\Iai\V20200303\Models\GetGroupInfoRequest;  //获取人员库信息
use TencentCloud\Iai\V20200303\Models\CreatePersonRequest;  //创建人员信息
use TencentCloud\Iai\V20200303\Models\VerifyPersonRequest;  //人脸对比
use TencentCloud\Iai\V20200303\Models\DeletePersonRequest;  //删除人员

class FaceID
{
    protected  $secret_id;
    protected  $secret_key;
    protected  $cred;
    protected  $client;
    public function __construct($secret_id = '',string $secret_key){
        $this->secret_id = $secret_id;
        $this->secret_key = $secret_key;
        $this->cred = new Credential($secret_id,$secret_key);
        //设置节点
        $this->client = new FaceidClient($this->cred, "ap-guangzhou");
    }

    /**
     * 身份证照片校验
     * @date 2021/6/16
     * @param string $base64
     * @param array $config
     *  配置例如：$config=['CopyWarn'=>true];
     *  CopyWarn，复印件告警
        BorderCheckWarn，边框和框内遮挡告警
        ReshootWarn，翻拍告警
        DetectPsWarn，PS检测告警
        TempIdWarn，临时身份证告警
        Quality，图片质量告警（评价图片模糊程度）
     * @author MrGuo
     */
    function checkIdCardInformation(string $base64,array $config=[]){

        $req = new CheckIdCardInformationRequest();
        $req->setImageBase64($base64);
        if(!empty($config)){
            $req->setConfig(json_encode($config));
        }
        try{
            $resp=$this->client->CheckIdCardInformation($req);
            return json_decode($resp->toJsonString(),true);
//            {
//                Address: "四川省珙县仁xxxxxxxx"
//                Birth: "1994/8/16"
//                Description: "成功"
//                IdNum: "511xxxxxxxxxxxx2517"
//                Name: "郭xx"
//                Nation: "汉"
//                Portrait: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQ"
//                Quality: 0
//                RequestId: "0fabb522-9ff4-4215-b81f-ced6cce80bcc"
//                Result: "Success"
//                Sex: "男"
//                Sim: 96.19
//                Warnings: ""
//            }
        }catch (\Exception $e){
            return ['errors'=>$e->getMessage()];
        }

    }

    /**
     * 身份证号码+真实姓名校验
     * @date 2021/6/16
     * @author MrGuo
     * @param string $truename
     * @param string $idcard
     * @return array|bool|float|int|mixed|\stdClass|string|\要转换的数据|null
     */
    public function checkIdCardVerification(string $truename,string $idcard,array $config = []){
        $req = new IdCardVerificationRequest();
        $req->setName($truename);
        $req->setIdCard($idcard);
        if(!empty($config)){
            $req->setConfig(json_encode($config));
        }
        try{
            $resp=json_decode($this->client->IdCardVerification($req)->toJsonString(),true);
            if(isset($resp['Result'])&&intval($resp['Result'])==0){
                return true;
            }
            return false;
        }catch (\Exception $e){
            Log::record("身份证号码+真实姓名校验失败" . $e->getMessage());
            return false;
        }
    }

    /**
     * 人脸对比
     * @date 2021/6/16
     * @author MrGuo
     */
    public function  faceToFace($user,$post)
    {
        $this->client = new IaiClient($this->cred, "ap-guangzhou");
        $req = new GetGroupInfoRequest();
        $req->setGroupId(md5(config('api.group_name')));

        if(!$user['rerson_id']){
            try{
                $res = json_decode($this->client->GetGroupInfo($req)->toJsonString(),true);
            }catch (\Exception $e){
                $req = new CreateGroupRequest();
                $req->setGroupName(config('api.group_name'));  //人员库名称
                $req->setGroupId(md5(config('api.group_name')));  //人员库id
                try{
                    $res = json_decode($this->client->CreateGroup($req)->toJsonString(),true);
                }catch(\Exception $e){
                    Log::record("人脸识别失败" . $e->getMessage());
                    return false;
                }
            }
            $req = new CreatePersonRequest();
            $req->setGroupId(md5(config('api.group_name')));
            $req->setPersonName(md5($user['unionid']));
            $req->setPersonId(md5($user['unionid']));
            $req->setUrl($post['avatarUrl']);
            try{
                $res = json_decode($this->client->CreatePerson($req)->toJsonString(),true);
                $user->rerson_id = md5($user['unionid']);
                $user->save();
            }catch(\Exception $e){
                Log::record("人脸识别失败" . $e->getMessage());
                return false;
            }
        }
        $req = new VerifyPersonRequest();
        $req->setPersonId($user->rerson_id);
        $req->setUrl($post['avatarUrl_real']);
        try{
            $res = json_decode($this->client->VerifyPerson($req)->toJsonString(),true);
            return (int)$res['Score'];   //这里直接取整相似度
        }catch(\Exception $e){
            Log::record("人脸识别失败" . $e->getMessage());
            return false;
        }
    }
    /**
     * 删除人员
     * [deletePerson description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public function deletePerson($user){
        $this->client = new IaiClient($this->cred, "ap-guangzhou");
        $req = new DeletePersonRequest();
        $req->setPersonId(md5($user['unionid']));
        try{
            $res = json_decode($this->client->DeletePerson($req)->toJsonString(),true);
            return true;
        }catch(\Exception $e){
            return false;
        }
    }
}
